from flask import Flask
from flask_mysqldb import MySQL

mysql = MySQL()


def create_app():
    app = Flask(__name__)
    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = '123456'
    app.config['MYSQL_DB'] = 'blood_sugar'
    app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

    mysql.init_app(app)
    return app


app = create_app()


def get_db_connection():
    """获取数据库连接"""
    if not app:
        raise RuntimeError('Flask应用未初始化')
    return mysql.connection


def test_db_connection():
    try:
        with app.app_context():
            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT 1')
            result = cursor.fetchone()
            print(f"数据库连接测试成功: {result}")
            cursor.close()
    except Exception as e:
        print(f"数据库连接失败: {str(e)}")


if __name__ == '__main__':
    test_db_connection()